package com.rp;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.rp.data.tcp_ws.server_tcp.NettyServerTcp;
import com.rp.data.tcp_ws.server_ws.NettyServerWs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
        (exclude = {
                DruidDataSourceAutoConfigure.class,
                SecurityAutoConfiguration.class
        })
@EnableScheduling
//开启缓存
@EnableCaching
@Slf4j
@ServletComponentScan
public class DrawApplication extends SpringBootServletInitializer implements CommandLineRunner {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DrawApplication.class);
    }
    @Autowired
    private NettyServerWs nettyServerWs;

    @Value("${ws.port}")
    private Integer wsPort;

    @Value("${ws.enable}")
    private Boolean wsEnable;

    @Autowired
    private NettyServerTcp nettyServerTcp;

    @Value("${tcp.port}")
    private Integer tcpPort;

    @Value("${tcp.enable}")
    private Boolean tcpEnable;

    public static void main(String[] args) {
        SpringApplication.run(DrawApplication.class, args);
    }
    @Override
    public void run(String... args) throws Exception {
        log.info("服务器启动");
        if (wsEnable) {
            openWs();
        }
        if (tcpEnable) {
            openNetty();
        }
    }

    public void openWs() {
        try {
            //开启 netty 服务
            new Thread(() -> {
                try {
                    Thread.sleep(5000);
                    this.nettyServerWs.start(wsPort);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void openNetty() {
        new Thread(() -> {
            try {
                //开始启动netty服务
                // 绑定服务端口监听
                Thread.sleep(5000);
                this.nettyServerTcp.start(tcpPort);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}
